window.babAddonWidgets.addGroupSelection = function(domNode)
{
	jQuery(domNode).find('.widget-acl').each(function(index, widget) { 
		widget = jQuery(widget);
		var meta = window.babAddonWidgets.getMetadata(widget.attr('id'));
		
		var frame = jQuery('<div class="widget-acl-frame"><strong></strong></div>');
		frame.find('strong').text(widget.attr('title'));
	
		var button = jQuery('<button><img src="ovidentia/styles/addons/widgets/images/22x22/add_group.png" /></button>');
		button.attr('title', meta.buttonText);
		frame.append(button);
		
		var list = jQuery('<ul></ul>');
		if (meta.maxHeight)
		{
			list.css('max-height', meta.maxHeight+meta.maxHeightUnit);
		}
		frame.append(list);
		
		frame.insertAfter(widget);
	
		window.babAddonWidgets.updateList(widget);
	
		button.click(function() {
			
			var input = jQuery(this).closest('.widget-acl-frame').prev('input');
	
			// open dialog
			
			var page = jQuery('<div class="widget-acl-dialog"><ul class="root"></ul></div>');
			
			page.attr('title', input.attr('title'));
			
			page.dialog({
				'width': jQuery(window).width() - 80,
				'height': jQuery(window).height() - 80,
				'modal': true, 
				'buttons': 
					[{
						text: "Ok",
			           	click: function() {
							// serialize checked groups
						
							window.babAddonWidgets.updateGroups(input, jQuery(this));
							jQuery(this).dialog("close"); 
						}
					}]
			});
			
			window.babAddonWidgets.fillGroups(input, page.find('ul.root'), 0, 1);
		});
	});
}



window.babAddonWidgets.updateList = function(widget)
{
	var meta = window.babAddonWidgets.getMetadata(widget.attr('id'));
	var ul = widget.next('div').find('ul');
	ul.addClass('loading');
	var groups = widget.attr('value');
	
	
	jQuery.ajax({
	   url: meta.selfpage,
	   data: 'tg=addon/widgets/groups&idx=infos&groups='+encodeURIComponent(groups)+'&uid='+encodeURIComponent(meta.uid),
	   success: function(response) {
			ul.removeClass('loading');
			
			if ('[' == response.substr(0,1)) {

				eval('var groups = '+response+';');
				var g = null;
				
				
				ul.find('li').map(function() 
				{
					var li = jQuery(this);
					remove = true;
					for(var i = 0; i < groups.length; i++)
					{
						if (groups[i].id == li.data('group').id && groups[i].withChildNodes == li.data('group').withChildNodes)
						{
							// li found in response, do not remove li
							remove = false;
							break;
						}
					}
					
					if (remove)
					{
						li.remove();
					}
				});
				
				

				for(var i = 0; i < groups.length; i++)
				{
					if (groups[i].withChildNodes)
					{
						g = groups[i].id+'a';
					} else {
						g = groups[i].id+'b';
					}
					
					

					if (ul.find('li.widget-acl-group-'+g).length > 0)
					{
						// allready inserted
						continue;
					}
					
					var li = jQuery('<li><div class="group"><span></span><br /><em></em><br /></div><div class="delete"></div></li>');
					li.data('group', groups[i]);
					li.addClass('widget-acl-group-'+g);
					li.find('span').text(groups[i].name);
					if (groups[i].withChildNodes)
					{
						li.find('em').text(meta.withChildNodes);
					}
					
					if (groups[i].setOfGroups)
					{
						li.find('em').text(meta.setOfGroups);
					}
					
					ul.append(li);
					
					li.find('.delete').attr('title', meta.deleteTitle);
					
					li.find('.delete').click(function() {
						
						var id_group = jQuery(this).closest('li').data('group').id;
						var input = jQuery(this).closest('.widget-acl-frame').prev('input');
						
						var value = input.attr('value').split(',').map(function(x) {

							if (x == id_group || x == id_group+'+')
							{
								return null;
							}
							
							return x;
						}).join(',');
						input.attr('value', value);
						jQuery(this).closest('li').remove();
					});
				}
				
				
			} else {
				if(response.length < 2048) {
					alert(response);
				} else {
					alert('error');
				}
			}
	   }
	});
	
}




window.babAddonWidgets.isChecked = function(input, id_group, withChildNodes)
{
	if (withChildNodes)
	{
		id_group = id_group+'+';
	}
	
	var groups = input.attr('value').split(',');
	for(var i=0; i<groups.length; i++)
	{
		if (groups[i] == id_group)
		{
			return true;
		}
	}
	
	return false;
}

window.babAddonWidgets.updateGroups = function(input, dialog)
{
	// do not remove from input the id not processed in dialog
	
	var groups = input.attr('value').split(',');
	var indialog = new Array();
	var checked = new Array();
	var groupid = null;
	dialog.find('input').each(function(index, input) {
		
		input = jQuery(input);
		
		if (input.attr('name').indexOf('tree') != -1)
		{
			groupid = input.attr('value')+'+';
		} else {
			groupid = input.attr('value');
		}
		
		indialog.push(groupid);
		
		if (input.is(':checked') && !input.is(':disabled'))
		{
			checked.push(groupid);
		}
	});
	
	// remove processed item
	groups = jQuery.map(groups, function(g) {
		
		if ('' == g)
		{
			return null;
		}
		
		for(var i=0; i<indialog.length; i++)
		{
			if (indialog[i] == g)
			{
				return null;
			}
		}
		
		return g;
	});
	
	
	
	// add checked items
	for(var i=0; i<checked.length; i++)
	{
		groups.push(checked[i]);
	}
	
	
	
	input.attr('value', groups.join(','));
	window.babAddonWidgets.updateList(input);
}







/**
 * get group ID from LI
 */
window.babAddonWidgets.getGroupId = function(li)
{
	var id = jQuery(li.find('input')[0]).attr('value');
	
	return id;
}


/**
 * @param	jQuery	input			input text field
 * @param	jQuery 	ul				target ul to insert nodes
 * @param	int		id_parent		parent group
 * @param	int		levels			number of levels to get in request
 */
window.babAddonWidgets.fillGroups = function(input, ul, id_parent, levels)
{
	// get groups from id_parent
	
	var meta = window.babAddonWidgets.getMetadata(input.attr('id'));
	
	jQuery.ajax({
	   url: meta.selfpage,
	   data: 'tg=addon/widgets/groups&idx=get&id_parent='+id_parent+'&uid='+meta.uid+'&levels='+levels,
	   success: function(response){
			if ('[' == response.substr(0,1)) {
				
				eval('var groups = '+response+';');
				
				var parent = ul.prev('li').find('[name="group_tree[]"]');
				
				
				for(var i=0; i<groups.length; i++)
				{
					var li = jQuery('<li><strong></strong><div class="list-item"><input type="checkbox" name="group_tree[]" value="'+groups[i].id+'" /><span></span></div> <div class="eol"><input type="checkbox" name="group[]" value="'+groups[i].id+'" /> </div></li>');
					li.find('span').text(groups[i].name);
					var group_tree = li.find('[name="group_tree[]"]');
					var group = li.find('[name="group[]"]');
					
					if (window.babAddonWidgets.isChecked(input, groups[i].id, true))
					{
						group_tree.attr('checked','checked');
					}
					
					if (window.babAddonWidgets.isChecked(input, groups[i].id, false))
					{
						group.attr('checked','checked');
					}
					
					if (parent.is(':checked'))
					{
						group_tree.attr('checked','checked');
						group.attr('checked','checked');
						group_tree.attr('disabled','disabled');
						group.attr('disabled','disabled');
					}
					
					if (groups[i].setOfGroups)
					{
						group_tree.css({"visibility":"hidden"});
					}
					
					
					ul.append(li);
					
					group_tree.click(function() {
						
						var c = jQuery(this).closest('li').next('ul').find('input[type=checkbox]');
						c.push(jQuery(this).closest('div').nextAll('.eol').find('input[type=checkbox]')[0]);
						
						if (jQuery(this).is(':checked'))
						{
							c.attr('disabled', 'disabled');
							c.attr('checked', 'checked');
						} else {
							c.removeAttr('disabled');
							c.removeAttr('checked');
						}
					});
					
					
					// add a + if the group have child nodes
					
					if (groups[i].hasChildNodes)
					{
						var plus = li.find('strong');
						plus.attr('class','plus');
						plus.click(function() {
							
							var li = jQuery(this).closest('li');
							
							if (jQuery(this).hasClass('plus'))
							{
								if (!li.next('ul,li').is('ul'))
								{
									jQuery(this).attr('class','loading');
									var ul = jQuery('<ul></ul>');
									ul.insertAfter(li);
									window.babAddonWidgets.fillGroups(input, ul, window.babAddonWidgets.getGroupId(li), 1);
								} else {
									li.next('ul').show();
									jQuery(this).attr('class','minus');
								}
								
								
							} else {
								
								li.next('ul').hide();
								jQuery(this).attr('class','plus');
							}
							
						});
					}
				}
				
				// set the minus class on parent checkbox
				
				if (!ul.hasClass('root'))
				{
					ul.prev('li').find('strong').attr('class', 'minus');
				}

			} else {
				if(response.length < 2048) {
					alert(response);
				} else {
					alert('error');
				}
			}
	   }
	});
}




window.babAddonWidgets.init = function(domNode)
{
	// hide default field
	
	jQuery(domNode).find('.widget-acl').hide();
	
	// add group selection
	
	window.babAddonWidgets.addGroupSelection(domNode);
}



window.bab.addInitFunction(window.babAddonWidgets.init);


